﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Thingpower.SS.EduOnline.Model;
using Thingpower.SS.EduOnline.Provider;
using Thingpower.SS.EduOnline.Core;

namespace Thingpower.SS.EduOnline.WebAPI
{
    [RoutePrefix("eduonline/api/coursewares")]
    public class CoursewaresController : ApiController
    {
        [HttpGet, Route("hello")]
        public IHttpActionResult GetString()
        {
            return Ok("hello");
        }

        #region 添加报名
        [HttpPost, Route("enroll")]
        public IHttpActionResult AddEnrollment(dynamic jsonModel)
        {
            //var request = EduOnlinePlugin.Instance.PluginApi.AuthRequest(HttpContext.Current.Request);

            var _model = new EnrollmentInfo();
            _model.CoursewareId = jsonModel.coursewareId;
            _model.UserId = jsonModel.userId;
            _model.AddDate = DateTime.Now;

            return Ok(EnrollmentDAO.Insert(_model));
        }
        #endregion

        #region 通过userid和coursewareid获取报名
        [HttpGet, Route("enroll")]
        public IHttpActionResult GetEnrollment(int userId, int coursewareId)
        {
            //var request = EduOnlinePlugin.Instance.PluginApi.AuthRequest(HttpContext.Current.Request);

            EnrollmentInfo _model = null;
            _model = EnrollmentDAO.GetModel(userId, coursewareId);

            if(_model == null)
            {
                return NotFound();
            }
            else
            {
                return Json<EnrollmentInfo>(_model);
            }
            
        }
        #endregion

        #region 添加学习日志
        [HttpPost, Route("log")]
        public IHttpActionResult AddStudyLog(dynamic jsonModel)
        {
            //var request = EduOnlinePlugin.Instance.PluginApi.AuthRequest(HttpContext.Current.Request);

            var _model = new StudyLogInfo();
            _model.CoursewareId = jsonModel.coursewareId;
            _model.UserId = jsonModel.userId;
            _model.AddDate = DateTime.Now;

            return Ok(StudyLogDAO.Insert(_model));
        }
        #endregion

        #region 搜索课件
        [HttpGet, Route("search")]
        public IHttpActionResult SearchCoursewares([FromUri]string query)
        {
            if (Utils.IsAttack(query))
            {
                return NotFound();
            }
            else
            {
                try
                {
                    return Ok(CoursewareDAO.GetModelList($"title like '%{query}%'"));
                }
                catch (Exception)
                {
                    return NotFound();
                }
                
            }
        }
        #endregion
    }
}